package com.liang.security.springboot.controller;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author liang zai
 * @date 2021/8/31 15:49
 * @description
 */
@RestController
public class LoginController {



    @RequestMapping(value = "/login-success",produces = {"text/plain;charset=UTF-8"})
    public String loginSuccess(){
        return getUsername()+" 登录成功";
    }

    /**
     * 测试资源1
     */
    @GetMapping(value = "/r/r1", produces = {"text/plain;charset=utf-8"})
    @PreAuthorize("hasAuthority('p1')")//拥有p1资源才可以访问
    public String r1(){
        return getUsername()+"访问资源R1";
    }

    /**
     * 测试资源2
     */
    @GetMapping(value = "/r/r2", produces = {"text/plain;charset=utf-8"})
    @PreAuthorize("hasAuthority('p2')")//拥有p1资源才可以访问
//    @PreAuthorize("hasAnyAuthority('p1','p2')")
    public String r2(){
        return getUsername()+"访问资源R2";
    }


    /**
     * 获取当前登录用户名
     * @return
     */
    public String getUsername() {
        //当前认证通过的用户身份
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (!authentication.isAuthenticated()) {
            return null;
        }
        //用户身份
        Object principal = authentication.getPrincipal();
        String username = null;
        if (principal == null) {
            username = "匿名";
        }
        if (principal instanceof UserDetails) {
             username = ((UserDetails) principal).getUsername();
        } else {
            username = principal.toString();
        }
        return username;
    }


}
